package com.hfdg.process.ctrl;

import com.alibaba.fastjson.JSONObject;
import com.hfdg.process.service.ProcessDataService;
import com.hfdg.prototype.base.model.AjaxResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.engine.FormService;
import org.flowable.engine.ManagementService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ProcessCtrl
 * @Description TODO
 * @Author yuelh
 * @Date 2020-2-3 22:16
 * @Version 1.0
 * @Company 会飞的锅工作室
 **/
@Controller
@RequestMapping("/process")
public class ProcessCtrl {
    @Autowired
    RepositoryService repositoryService;
    @Autowired
    RuntimeService runtimeService;
    @Autowired
    FormService formService;
    @Autowired
    ProcessDataService processDataService;
    @Autowired
    ManagementService managementService;

    @Autowired
    MongoTemplate mongoTemplate;
    /*
     * @Author yuelh
     * @Company tzstcl
     * @Description //TODO  流程发起
     * @Date 23:32 2020-2-3
     * @Param [processKey：流程key, formName:表单名称，用以标识mongodb存储即可, formData：具体表单数据,
     * processData：流程变量数据，主要用于控制流程网关判断以及下一步办理人处理]
     * @return com.hfdg.prototype.base.model.AjaxResult
     **/
    @RequestMapping("/toStartFormView")
    public String toStartFormView(String processDefinitionId,Model model){
        ProcessDefinition processDefinition =  repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).latestVersion().singleResult();
        model.addAttribute("processDefinitionId",processDefinitionId);
        model.addAttribute("processKey",processDefinition.getKey());
        model.addAttribute("processName",processDefinition.getName());
        model.addAttribute("fragment","startFormOperation");
        return "/commons/process/form/"+processDefinition.getKey();
    }

    /**
     *  跳转至办理页面
     * @param taskId
     * @param model
     * @return
     */
    @RequestMapping("/toProcessView")
    public String toProcessView(String taskId,Model model){




        List<Map<String,Object>> processHistoryList = new ArrayList<Map<String,Object>>();
        Map<String,Object> processHistory = new HashMap<>();
        processHistory.put("taskName","部门经理审批");
        processHistory.put("assignee","办理人");
        processHistory.put("processTime","处理时间");
        processHistory.put("operation","流转");
        processHistory.put("opinion","请有关同志抓紧时间进行落实。");
        Map<String,Object> processHistory1 = new HashMap<>();
        processHistory1.put("taskName","部门经理审批");
        processHistory1.put("assignee","办理人");
        processHistory1.put("processTime","处理时间");
        processHistory1.put("operation","流转");
        processHistory1.put("opinion","我处已经安排专门人员尽快抓紧时间办理");
        processHistoryList.add(processHistory);
        processHistoryList.add(processHistory1);
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
//        ClassPathResource classPathResource = new ClassPathResource("ftl");

        try {
//            cfg.setDirectoryForTemplateLoading(new File("C:\\home\\develop\\workspace4idea\\hfdg-prototype\\src\\main\\resources\\ftl"));
            cfg.setClassForTemplateLoading(this.getClass(),"/ftl");
            //这是模板的编码
            cfg.setDefaultEncoding("UTF-8");
            Template template = cfg.getTemplate("processHistory.ftl");
            StringWriter stringWriter = new StringWriter();
            Map<String,Object> root = new HashMap<>();
            root.put("processHistoryList",processHistoryList);
            template.process(root,stringWriter);
            model.addAttribute("processHistory",stringWriter.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }


        return "/commons/process/form/";
    }

    /**
     *
     * @param processData 流程信息，流程定义ID，流程key，流程名称
     * @param formData
     * @return
     */
    @RequestMapping("/saveFormData")
    @ResponseBody
    public AjaxResult saveFormData(String processData,String formData){
        JSONObject processMap =JSONObject.parseObject(processData);
        processMap.put("formData",formData);
        mongoTemplate.insert(processMap,processMap.get("processKey")+"");
        return AjaxResult.success();
    }

    @RequestMapping("/start")
    @ResponseBody
    public AjaxResult start(String processData, String formData, String handlerData, HttpServletRequest request){
        Authentication.setAuthenticatedUserId(request.getSession().getAttribute("uid")+"");
        JSONObject processMap = JSONObject.parseObject(processData);
        JSONObject formDataMap=JSONObject.parseObject(formData);
        JSONObject handlerDataMap=JSONObject.parseObject(handlerData);
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processMap.get("processDefinitionId")+"",handlerDataMap);
        processMap.put("formData",formData);
        processMap.put("processInstanceId",processInstance.getId());
        mongoTemplate.insert(processMap,processMap.get("processKey")+"");
        return AjaxResult.success();
    }
    /*
     * @Author yuelh
     * @Company tzstcl
     * @Description //TODO  退回流程
     * @Date 0:04 2020-2-4
     * @Param []
     * @return com.hfdg.prototype.base.model.AjaxResult
     **/
    @RequestMapping("/sendBack")
    @ResponseBody
    public AjaxResult sendBack(){
        return AjaxResult.success();
    }


    public AjaxResult complete(String processInstanceId,String deleteReason){
        runtimeService.deleteProcessInstance(processInstanceId,deleteReason);
        return AjaxResult.success();
    }


    @RequestMapping("/getPagingProcessDefinition")
    @ResponseBody
    public AjaxResult getPagingProcessDefinition(int offset, int limit, String orderBy, Map<String, Object> params){
        return AjaxResult.success(processDataService.getPagingProcessDefinition(offset,limit,orderBy,params));
    }

    @RequestMapping("/toProcessDefinitionListView")
    public String toProcessDefinitionListView(){
        return "commons/process/processDefinitionListView";
    }




}
